package com.guojiang.guoaicodemother.manager;

import com.guojiang.guoaicodemother.config.CosClientConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * COS 对象存储通用管理类
 */
@Component
@Slf4j
public class CosManager {

    /**
     * 配置
     */
    @Resource
    private CosClientConfig cosClientConfig;

    /**
     * COS 客户端（用于进行实际操作）
     */
    @Resource
    private COSClient cosClient;

    /**
     * 上传对象
     *
     * @param key
     * @param file
     * @return
     */
    public PutObjectResult putObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, file);
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 上传文件到 COS，并返回可访问的 URL 地址
     *
     * @param key
     * @param file
     * @return
     */
    public String uploadFileAndReturnUrl(String key, File file) {
        PutObjectResult putObjectResult = putObject(key, file);
        if (putObjectResult != null) {
            String url = String.format("%s/%s", cosClientConfig.getHost(), key);
            log.info("文件 {} 上传到 COS {} 成功", file.getName(), url);
            return url;
        }
        log.error("文件 {} 上传到 COS 失败，", file.getName());
        // 返回 null，交给外层处理
        return null;
    }
}
